import { useStore } from 'vuex'
import { computed } from 'vue'
import { save } from '@/assets/js/array-store'
import { FAVORITE_KEY } from '@/assets/js/constant'
export default function useFavorite () {
  const store = useStore()
  const favoriteList = computed(() => store.state.favoriteList)

  function isFavorite (song) {
    return (
      favoriteList.value?.findIndex((favorite) => favorite.id === song.id) > -1
    )
  }
  function getFavoriteIcon (song) {
    return isFavorite(song) ? 'icon-favorite' : 'icon-not-favorite'
  }
  function toggleFavorite (song) {
    let list
    if (isFavorite(song)) {
      // remove
    } else {
      // save compare：函数
      list = save(song, FAVORITE_KEY, (item) => {
        // song：切换的歌曲
        return item.id === song.id
      })
    }
    store.commit('setFavoriteList', list)
  }
  return {
    getFavoriteIcon,
    toggleFavorite
  }
}
